package com.monkey.imageselect;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.ace.ability.AceInternalAbility;
import ohos.app.AbilityContext;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.photokit.metadata.AVStorage;
import ohos.rpc.IRemoteObject;
import ohos.rpc.MessageOption;
import ohos.rpc.MessageParcel;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;
import ohos.utils.zson.ZSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查找本地图片，并返回js
 */
public class ImageDataInternalAbility extends AceInternalAbility {
    private static final HiLogLabel LABEL = new HiLogLabel(0, 0, "ImageDataInternalAbilit.class");
    private static final String BUNDLE_NAME = "com.monkey.imageselect";
    private static final String ABILITY_NAME = "ImageDataInternalAbility";

    private static final int SUCCESS = 0;
    private static final int ERROR = 1;

    private static final int LOAD_IMAGE = 1001;


    private static ImageDataInternalAbility instance;
    private AbilityContext abilityContext;

    private ImageDataInternalAbility() {
        super(BUNDLE_NAME, ABILITY_NAME);
    }

    /**
     * js-java通信
     *
     * @param code   js-java通信code码
     * @param data   js传递给java的通信数据
     * @param reply  java写给js的通信数据
     * @param option 消息类型
     * @return
     */
    public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
        //加载数据
        Map<String, Object> result = new HashMap<>();
        if (code == LOAD_IMAGE) {
            result.put("code", SUCCESS);
            try {
                List<String> list = loadImage();
                result.put("data", list);
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }
            // SYNC
            if (option.getFlags() == MessageOption.TF_SYNC) {
                reply.writeString(ZSONObject.toZSONString(result));
            } else if (option.getFlags() == MessageOption.TF_ASYNC) {
                // ASYNC
                MessageParcel responseData = MessageParcel.obtain();
                responseData.writeString(ZSONObject.toZSONString(result));
                IRemoteObject remoteReply = reply.readRemoteObject();
                try {
                    remoteReply.sendRequest(0, responseData, MessageParcel.obtain(), new MessageOption());
                } catch (RemoteException exception) {
                    return false;
                } finally {
                    responseData.reclaim();
                }
            }
        } else {
            result.put("code", ERROR);
            result.put("message", "error");
            reply.writeString(ZSONObject.toZSONString(result));
            return false;
        }
        return true;
    }

    /**
     * 注册
     * @param abilityContext 上下文
     */
    public void onRegister(AbilityContext abilityContext) {
        this.abilityContext = abilityContext;
        this.setInternalAbilityHandler(this::onRemoteRequest);
    }

    /**
     * 实例化-单例
     *
     * @return ImageDataInternalAbility
     */
    public static ImageDataInternalAbility getInstance() {
        if (instance == null) {
            synchronized (ImageDataInternalAbility.class) {
                if (instance == null) {
                    instance = new ImageDataInternalAbility();
                }
            }
        }
        return instance;
    }

    /**
     * 取消注册
     */
    public void onUnregister() {
        abilityContext = null;
        this.setInternalAbilityHandler(null);
    }


    //加载本地图片
    private List<String> loadImage() throws DataAbilityRemoteException {
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(abilityContext);
        ResultSet resultSet = dataAbilityHelper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null);

        List<String> list = new ArrayList<>();
        //遍历结果集
        while (resultSet != null && resultSet.goToNextRow()) {
            //通过指定的下标获取列索引，通过获得的列索引获取到该图片的资源id。
            int mediaId = resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Images.Media.ID));
            //将图片id转换为Uri类型
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, mediaId + "");

            list.add(uri.toString());
            //HiLog.error(LABEL,uri.toString());
        }
        return list;
    }
}
